<?php
/**
 * @description:
 * @author     : Geomen
 * @time       : 2018/12/19 10:53
 */


namespace App\Component;


use App\Models\FormId;

class WeiXin
{
    /**
     * 获取accessToken
     */
    public function getAccessToken()
    {
        $access_token = '';
        $file = storage_path('access_token.json');
        if (file_exists($file)){ //文件存在
            $info = file_get_contents($file);
            if (strlen($info) == 0){ //空文件
                $info = self::getAccessTokenFromWeiXin();
                if (isset($info['access_token'])) {
                    $access_token = $info['access_token'];
                }
            }else{
                $info = json_decode($info,true);
                if ($info['expire_time'] < time()) { //过期
                    $info = self::getAccessTokenFromWeiXin();
                    if (isset($info['access_token'])) {
                        $access_token = $info['access_token'];
                    }
                }else{
                    $access_token = $info['access_token'];
                }
            }
        }else {
            $body   = self::getAccessTokenFromWeiXin();
            if (isset($body['access_token'])) {
                $access_token = $body['access_token'];
            }
        }
        return $access_token;
    }

    /**
     * 从微信获取accessToken
     */
    public function getAccessTokenFromWeiXin()
    {
        $file = storage_path('access_token.json');
        $url    = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . env('MINI_APPID') . '&secret=' . env('MINI_APPSECRET');
        $result = \Requests::get($url);
        $body = json_decode($result->body, true);
        if (isset($body['errcode'])){
            if ($body['errcode'] == -1) {
                return self::getAccessTokenFromWeiXin();
            }
        }else{
            $body['expire_time'] = time() + $body['expires_in'] - 10;
            file_put_contents($file, json_encode($body));
        }
        return $body;
    }

    /**
     * 获取最旧的表单ID
     *
     * @param string $open_id
     *
     * @return mixed
     */
    public function getOldFormId($open_id = '')
    {
        return FormId::query()->where('open_id',$open_id)->where('expire_time','>',time())->oldest('id')->value('form_id');
    }

    /**
     * 发送模板消息
     *
     * @param string $open_id
     * @param string $template
     * @param string $page
     * @param array  $params
     * @param string $emphasis_keyword
     *
     * @return array|mixed
     */
    public function sendTemplateMessage($open_id = '',$template = '',$page = '',$params = [],$emphasis_keyword = '')
    {
        $form_id = self::getOldFormId($open_id);
        if (!$form_id) {
            return ['errcode' => 2000, 'errmsg' => '无可用的formId'];
        }
        $data = array();
        foreach ($params as $key => $item) {
            $data['keyword'.($key+1)] = ['value' => $item];
        }
        $postData = array(
            'touser' => $open_id,
            'template_id' => $template,
            'page' => $page,
            'form_id' => $form_id,
            'data' => $data,
            'emphasis_keyword' => $emphasis_keyword
        );
        $access_token = self::getAccessToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$access_token;
        $res = \Requests::post($url,[],json_encode($postData));
        $resArr = json_decode($res->body,true);
        if (isset($resArr['errcode']) && in_array($resArr['errcode'],[0,41028,41029])){
            FormId::query()->where('form_id',$form_id)->delete();
        }
        return $resArr;
    }
}